package order

import (
	"context"
	"gitee.com/enjoy_5/order-rpc/internal/sever/order"
	"gitee.com/enjoy_5/order-rpc/internal/sever/produc"
	proto "gitee.com/enjoy_5/order-rpc/proto/order"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type OrdersInfoService struct {
	proto.UnimplementedOrderServer
}

func (o *OrdersInfoService) CreateOrder(ctx context.Context, in *proto.CreateOrderRequest) (*proto.CreateOrderResponse, error) {
	if in.GetIn().OrderNo == "" {
		return nil, status.Errorf(codes.InvalidArgument, "订单号不能为空")
	}
	if in.GetIn().UserId == 0 {
		return nil, status.Errorf(codes.InvalidArgument, "用户id不能为空")
	}
	if in.GetIn().Amount == "" {
		return nil, status.Errorf(codes.InvalidArgument, "金额不能为空")
	}
	create, err := order.CreateOrder(in.In)
	if err != nil {
		return nil, err
	}
	return &proto.CreateOrderResponse{Info: create}, nil
}
func (o *OrdersInfoService) DeleteOrder(ctx context.Context, in *proto.DeleteOrderRequest) (*proto.DeleteOrderResponse, error) {
	err := order.DeleteOrder(in.OrderId, in.UserId)
	if err != nil {
		return nil, err
	}
	return &proto.DeleteOrderResponse{}, nil
}
func (o *OrdersInfoService) OrderList(ctx context.Context, in *proto.OrderListRequest) (*proto.OrderListResponse, error) {
	list, err := order.GetOrderList(in.UserId, in.Status)
	if err != nil {
		return nil, err
	}
	return &proto.OrderListResponse{Info: list}, nil
}
func (o *OrdersInfoService) OrderListInfo(ctx context.Context, in *proto.OrderListInfoRequest) (*proto.OrderListInfoResponse, error) {
	list, err := produc.GetOrderGoodsList(in.OrderId)
	if err != nil {
		return nil, err
	}
	return &proto.OrderListInfoResponse{Info: list}, nil
}
func (o *OrdersInfoService) OrderUpdateStatus(ctx context.Context, in *proto.OrderUpdateStatusRequest) (*proto.OrderUpdateStatusResponse, error) {
	err := order.UpdateOrderStatus(in.OrderId, in.Status)
	if err != nil {
		return nil, err
	}
	return &proto.OrderUpdateStatusResponse{}, nil
}
func (o *OrdersInfoService) GetOrderInfo(ctx context.Context, in *proto.GetOrderInfoRequest) (*proto.GetOrderInfoResponse, error) {
	info, err := order.GetOrderInfo(in.OrderId)
	if err != nil {
		return nil, err
	}
	return &proto.GetOrderInfoResponse{Info: info}, nil
}

// 回滚创建订单
func (o *OrdersInfoService) RollbackOrderCreate(ctx context.Context, in *proto.CreateOrderRequest) (*proto.CreateOrderResponse, error) {
	err := order.RollCreateOrder(in.GetIn().OrderNo, in.GetIn().UserId)
	if err != nil {
		return nil, err
	}
	return &proto.CreateOrderResponse{}, nil
}
